package system

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"ruoyi_gin/app/admin/model/constants"
	"ruoyi_gin/app/admin/model/system"
	"ruoyi_gin/app/admin/model/tools"
	"ruoyi_gin/utils"
	"ruoyi_gin/utils/R"
	"strconv"
	"strings"
)

func ListUserApi(context *gin.Context) {
	pageNum, _ := strconv.Atoi(context.DefaultQuery("pageNum", "1"))
	pageSize, _ := strconv.Atoi(context.DefaultQuery("pageSize", "10"))

	deptId, _ := strconv.Atoi(context.DefaultQuery("deptId", "0"))
	var userName = context.DefaultQuery("userName", "")
	var status = context.DefaultQuery("status", "")

	var phonenumber = context.DefaultQuery("phonenumber", "")

	var beginTime = context.DefaultQuery("params[beginTime]", "")
	var endTime = context.DefaultQuery("params[endTime]", "")

	var param = tools.SearchTableDataParam{
		PageNum:  pageNum,
		PageSize: pageSize,
		Other: system.SysUser{
			DeptId:      deptId,
			UserName:    userName,
			Phonenumber: phonenumber,
			Status:      status,
		},
		Params: tools.ParamsX{
			BeginTime: beginTime,
			EndTime:   endTime,
		},
	}
	context.JSON(http.StatusOK, system.SelectUserList(param, true))
}

func LoginHandler(context *gin.Context) {
	var param system.LoginParam

	if err := context.ShouldBind(&param); err != nil {
		context.JSON(http.StatusOK, R.ReturnFailMsg("参数不能为空"))
		return
	} else {
		var captchaEnabled = system.SelectCaptchaEnabled()

		if captchaEnabled {
			isVerify := utils.VerifyCaptcha(param.Uuid, param.Code)

			if isVerify {
				isExit := system.IsExistUser(param.UserName)

				if isExit {

				}
			}
		}
	}

}

func FindUser(param system.LoginParam, ctx *gin.Context) {

	userName := param.UserName
	passWord := param.Password

	user := system.FinduserByName(userName)

	if user.UserId != 0 {

		if user.Status == "1" {
			ctx.JSON(http.StatusOK, R.ReturnFailMsg("账号已停用"))
			return
		}

		if utils.PasswordVerify(passWord, user.Password) {

			tokenString, err := utils.CreateToken(user.UserName, user.UserId, user.DeptId)

			if err != nil {
				ctx.JSON(http.StatusOK, R.ReturnFailMsg("登录失败"))
				return
			}
			ctx.JSON(http.StatusOK, gin.H{
				"msg":   "登录成功",
				"code":  http.StatusOK,
				"token": tokenString,
			})
		} else {
			ctx.JSON(http.StatusOK, gin.H{
				"msg":  "登录失败，密码错误",
				"code": http.StatusInternalServerError,
			})
		}
	} else {
		ctx.JSON(http.StatusOK, gin.H{
			"msg":  "用户不存在",
			"code": http.StatusInternalServerError,
		})
	}
}

// CaptchaImageHandler 验证码 输出

func CaptchaImageHandle1(context *gin.Context) {

	var captchaEnabled = system.SelectCaptchaEnabled()

	if captchaEnabled {
		id, b64s, _, err := utils.CreateImageCaptcha()
		if err != nil {
			context.JSON(http.StatusOK, R.ReturnFailMsg("创建二维码失败，请联系管理员"))
			return
		}
		context.JSON(http.StatusOK, gin.H{
			"msg":            "操作成功",
			"img":            strings.ReplaceAll(b64s, "data:image/png;base64,", ""),
			"code":           http.StatusOK,
			"captchaEnabled": captchaEnabled,
			"uuid":           id,
		})
	} else {
		context.JSON(http.StatusOK, gin.H{
			"msg":            "操作成功",
			"code":           http.StatusOK,
			"captchaEnabled": captchaEnabled,
		})
	}

}

func GetUserInfo(context *gin.Context) {
	userIdStr := context.Param("userId")
	loginUserId, _ := context.Get("userId")
	userId := utils.GetInterfaceToInt(loginUserId)
	if userIdStr == "" {
		userIdStr = strconv.Itoa(userId)
	}

	useridP, _ := strconv.Atoi(userIdStr)

	system.CheckUserDataScope(userId, useridP)

	user := system.FindUseById(useridP)
	var roles []system.SysRoles
	var roleIds []int
	// 登录者的权限
	roles = system.SelectRolePermissionByUserId(userId)

	var result = gin.H{
		"msg":   "操作成功",
		"code":  http.StatusOK,
		"data":  user,
		"roles": roles,
	}
	// 判断当期是否为管理员
	if useridP != 0 {
		roles2 := system.SelectRolePermissionByUserId(useridP)
		for _, sysRoles := range roles2 {
			roleIds = append(roleIds, sysRoles.RoleId)
		}
		result["roleIds"] = roleIds
	}

	context.JSON(http.StatusOK, result)
}

func GetInfoHandler(ctx *gin.Context) {

	userId, _ := ctx.Get("userId")

	user := system.FindUseById(userId)

	roles := system.GetRolePermission(user)

	permissions := system.GetMenuPermission(user)

	dept := system.GetDeptInfo(strconv.Itoa(user.UserId))

	ctx.JSON(http.StatusOK, gin.H{
		"msg":  "操作成功",
		"code": http.StatusOK,
		"user": gin.H{
			"userName":    user.UserName,
			"nickName":    user.NickName,
			"phonenumber": user.Phonenumber,
			"email":       user.Email,
			"avatar":      user.Avatar,
			"sex":         user.Sex,
			"createTime":  user.CreateTime,
			"dept":        dept,
		},
		"roles":       roles,
		"permissions": permissions,
	})
}

func PerfileHandler(ctx *gin.Context) {

	userId, _ := ctx.Get("userId")

	var user system.SysUser

	err := utils.MysqlDb.Where("user_id = ", userId).First(&user).Error

	if err != nil {

		ctx.JSON(http.StatusOK, R.ReturnFailMsg("未找到用户"))
		return
	}

	user.Password = ""
	ctx.JSON(http.StatusOK, gin.H{
		"msg":  "获取成功",
		"code": http.StatusOK,
		"data": gin.H{
			"userName":    user.UserName,
			"nickName":    user.NickName,
			"phonenumber": user.Phonenumber,
			"email":       user.Email,
			"sex":         user.Sex,
			"createTime":  user.CreateTime.Format(constants.TimeFormat),
		},
		"roleGroup": system.SelectRolesByUserName(user.UserName), // 目前暂时没有用
		"postGroup": system.SelectUserPostGroup(user.UserName),   // 目前暂时没有用
	})
}
